JavaScript Tutorial

by 
Hani Al-AbdulSalam
November 1999


Where to add JavaScript code in your HTML page !

                <INPUT TYPE="button"  VALUE="Hello"  onClick="document.write('Hello');">
Example 1
<HTML>
<HEAD>
	<TITLE>JavaScript Example </TITLE>
</HEAD>
<BODY>
   HTML Text goes here.
<SCRIPT LANGUAGE="JavaScript">
	document.write(" Here is my output. ")
</SCRIPT>
</BODY>
</HTML>

Variables

var myVariable;	// var is an option but it is recommended!
var intVar = 20;	// type of intVar will be integer
var strVar = "test string";	// type of strVar will be string 
var booleanVar = true;  	// type of booleanVar will be boolean
var myArray = new Array(20);	// create array of size 20 (0-19)
myArray[5] = 9;	
myArray[6] = "test";
var newArray = new Array("one","two");
var matrix = new Array(2);
matrix[0] = new Array(2);
matrix[1] = new Array(2);
matrix[0][0] = 1;
matrix[1][0] = 2;
matrix[0][1] = 3;
matrix[1][1] = 4;
var unknown;
unknown = 45;	// unknown become integer
unknown = "no it is string"	// unknown converted to string

a = parseInt("39 steps");	// a = 39
a = parsFloat("2.7178 is the base of a natural logarithm.");	// a = 2.7178
a = eval("20 + 1 + 4");		// a = 25
var u = String(23); // u = "23" 
var v = Number("44.55"); // v = 44.55 

Operations

Arithmetic + - * / % += -= *= /=
Relational < > <= >= == !=      
Logical && || !            
Unary + - ++ --          

 


Flow Controls    

if ( condition )
     statement or {block} ;
if ( x == 1 )
     y = 10;
if ( condition )
    statement or {block} ;
else
    statement or {block} ;
if ( x == 1 )
    y = 10 ;
else
    { y = 5;  z = 9 ;}
for ( setup; condition; change )
    statement or {block}
for ( i = 0; i <= 2; i++)
       document.write( i + ' ----  ' ) ;
while ( condition )
    statement or block
while (total < 10)
       { n++ ;   total ++  ; }
for ( i    in    object or array )
    statement or block
for (i in counters)
    { counters[i]++; }

break       Statement is used to exit the loop immediately and continue with the first statement after the loop.
continue Statement is used to skips the rest of the loop, but unlike break, it continues with the next iteration of the loop


Functions

function name(arguments)
{
    statements, possibly including 'return'
}
function add_fun(first, second)
{  
         var result = first + second;
         return result;
 }
how to call the function:
	name(arguments); 
or
	i = name(arguments);	//if it has "return"
example function calling the function
function Bold(text) {
   var temp = "<B>" + text + "</B>";
   return temp;
}
document.write( Bold ( "This is a test." ) ) ;
Example 2
<HTML>
<HEAD>
<TITLE>JavaScript</TITLE>
<SCRIPT language="JAVASCRIPT">
function PrintRow(name, age, birthday) {
   document.write("<TR> <TD>", name, "</TD> <TD>", age, "</TD> <TD>", birthday,"</TD> </TR>\n");
}
</SCRIPT>
</HEAD>
<BODY>
	<H1>Table Test Using JavaScript</H1>
	<TABLE>
	    <SCRIPT language="JAVASCRIPT">
		PrintRow("Fred", 27, "June 17");
		PrintRow("Tom", 24, "March 13");
		PrintRow("Jon", 25, "November 30");
	    </SCRIPT>
	</TABLE>
End of table.
</BODY>
</HTML>

Objects

function PrintHello() { document.write("Hello."); }
var myObject = new object;
myObject.name = "I am a newObject";
myObject.hello = "I can say hello";
myObject.printHello = PrintHello;

function displayCarInfo(){
    document.write("car Manufactural:" + this.name + "<BR>" + "car Model:" +
                    this.model + "-" + this.year);
}
function car(name,model,year){
    this.name = name;
    this.model = model;
    this.year = year;
}
myCar = new car("Toyota","Camry",1998);
myFriendCar = new car("Honda","Civic",1996);

Events

Event Name Description
onBlur
Occurs when an object on the page loses focus
onChange
Occurs when a text field is changed by the user
onClick
Occurs when the user clicks on an item
onFocus
Occurs when an item gains focus
onLoad
Occurs when the page (or an image) finishes loading
onMouseOver
Occurs when the mouse pointer moves over an item
onMouseOut
Occurs when the mouse pointer moves off an item
onSelect
Occurs when the user selects text in a text area
OnSubmit
Occurs when a submit button is pressed
OnUnload
Occurs when the user leaves the document or exits

example of using an event

    <A HREF="http://www.yahoo.com" onMouseOver="window.status=' Yahoo is an amazing search engine.'; return true">
                Click here to visit Yahoo
    </A>


Built-In Objects

Check: JavaScript Objects Map
String
String.length
return the length of the string
String.anchor("anchor")
    
String.charAt(index)
   
String.indexOf("string")
   
String.lastindexOf("string")
   
String.substring(start,end)
   
String.toLowerCase()
   
String.toUpperCase()
    
String.link("url")
link string to URL address
String.big()
displays big text, using the <BIG> tag
String.blink()
displays blinking text, using the <BLINK> tag
String.bold()
displays bold text, using the <B> tag
String.fixed()
displays fixed-font text, using the <TT> tag
String.fontcolor("color")
displays the string in a colored font, equivalent to the <FONTCOLOR> tag
String.fontsize(size)
changes the font size, using the <FONTSIZE> tag
String.italics()
displays the string in italics, using the <I> tag
String.small()
displays the string in small letters using the <SMALL>
String.strike()
displays the string in a strike-through font, using the <STRIKE> tag
String.sub()
displays subscript text, equivalent to the <SUB> tag
String.sup()
displays superscript text, equivalent to the <SUP> tag

a = "ABCDEFGHIJKLMN";
alpha.substring(0,4) returns "ABC".
alpha.charAt(12) returns "M".

Date
Date.get/setDate()
sets/gets the day of the month
Date.get/setMonth()
sets/gets the month. Months from 0 to 11, starting with January (0)
Date.get/setYear()
   
Date.get/setTime()
 in milliseconds since January 1st, 1970
Date.get/setHours()
      
Date.get/setMinutes()
      
Date.get/setSeconds()
       
Date.parse("date")
converts a date string, such as "May 20, 1999" to a Date object
D1 = new Date();
D2 = new Date("May 10, 1998 08:00:00");
D3 = new Date("December 20, 1998");

Example 3
Math
Math.abs(val)
get the absolute value of a number
Math.cos(val)
  
Math.sin(val)
   
Math.tan(val)
   
Math.sqrt(val)
   
Math.log(val)
   
Math.random()
   
Math.ceil(val)
rounds a number up to the next integer
Math.floor(val)
rounds a number down to the next integer
Math.round(val)
rounds a number to the nearest integer
Math.max(val1,val2)
return the maximum number
Math.min(val1,val2)
return the minimum number
Math.E
return the base of the natural logarithm (2.718)
Math.PI
return (3.14159)
Example 4
Navigator
Navigator.appcodeName
return the browser's code name, usually "Mozilla".
Navigator.appName
return the browser's name (Internet Explorer, Netscape, ...etc).
Navigator.appVersion
return the version of the browser.   
Navigator.platform
return the platform (e.g. "Win32")
other properties according to the browser.
Example 5
Location & Link
location.protocol
specifies the protocol to be used-world-wide web, gopher, and so forth ( e.g. http: ).
location.hostname
e.g. www.yahoo.com
location.port
e.g. 80
location.host
a combination of the host name and port ( e.g. www.yahoo.com:80 ).
location.pathname
specifies the directory to find the document on the host and the name of the file ( e.g. javascript/test.html ).
location.herf
the complete hyper reference. 
location.hash
the name of an anchor within the document  ( e.g. #part2 ).

Events  applicable for Link :  onClick, onMouseOver

Example 6: for Location  ,  Example 7: for Link
History
history.back()
go back to the previous location.
history.forward()
go forward to the next location.
history.go(int)
go to a specified location in the history list.
 
Window
window.open("url","name","options");
options = "width = n , height = n , toolbar = 1/0, status = 1/0, menubar= 1/0, scrollbars = 0/1, directories = 1/0"        { some browser accept "yes/no" instead of "1/0" }
window.close()
  
window.alert("message")
   
window.confirm("message")
   
window.prompt("message","default")
   
window.setTimeout("exp",delay)
   
clearTimeout(ID)
   

Event for Window :  onLoad, onUnload 

Example 8
<HTML>
<HEAD><TITLE>JS Example on the Window Object</TITLE>
<SCRIPT>
    var counter = 0;
    ID=window.setTimeout("Update();",1000);
    function Update() {
            counter ++;
            window.status="The counter is now at " + counter;
            document.form1.input1.value="The counter is now at " + counter;
            ID=window.setTimeout("Update();",1000);
    }
</SCRIPT>
</HEAD>
<BODY onLoad="window.alert('Welcome.');" onUnload="window.alert('YGoodbye!');">
    <FORM NAME="form1">
        <INPUT TYPE="text" NAME="input1" SIZE="40"><BR>
        <INPUT TYPE="button" VALUE="RESET" onClick="counter = 0;"><BR>
        <INPUT TYPE="button" VALUE="CLEAR" onClick="window.clearTimeout(ID);">
    </FORM>
</BODY>
</HTML>

Example 9
<HTML>
<HEAD>
<TITLE>JS Example on the Window Object </TITLE>
</HEAD>
<BODY>
<H3>Change the Status Line</H3>
Enter the text for the status line in the space below, then press
        the Change button to change it.
<FORM NAME="statform">
   <INPUT TYPE="text" SIZE="40" NAME="input1"><BR>
   <INPUT TYPE="button" VALUE="Change" onClick="window.status=document.statform.input1.value;">
</FORM><HR>
<H3>Create a New Window</H3>
<FORM NAME="winform">
     <INPUT TYPE="button" VALUE="Open New Window" onClick="NewWin=
        window.open('','NewWin', 'toolbar=no,status=no,width=300,height=200'); "><P>
    <INPUT TYPE="button" VALUE="Close New Window" onClick="NewWin.close();" ><P>
    <INPUT TYPE="button" VALUE="Close Main Window" onClick="window.close();">
</FORM><HR>
<H3>Alerts, Confirmations, and Prompts</H3>
<FORM NAME="winform">
    <INPUT TYPE="button" VALUE="Display an Alert" onClick=
        "window.alert('Alert test.');"><P>
    <INPUT TYPE="button" VALUE="Display a Confirmation"onClick=
            "temp=window.confirm('Confirm?');window.status=
            (temp)?'confirm:true':'confirm:false';"><P>
   <INPUT TYPE="button" VALUE="Display a Prompt" onClick=
            "var temp=window.prompt('Enter some Text:','default');
            window.status=temp;">
</FORM>
</BODY>
</HTML>
Document
document.title
 
document.bgColor
  
document.fgColor
   
document.linkColor
 
document.alinkColor
 
document.vlinkColor
 
document.forms[]
   
document.anchors[]
   
document.links[]
   
document.location
 
document.clear()
 
document.close()
 
document.writle(val)
 

 


Next


HTML Reference JavaScript Reference